import React, { useState } from 'react';
import { Rate, Spin, Empty } from 'antd';
import cn from 'classnames';
import request from '@/utils/request';
import { ScoreModal } from '../../../../components';
import { modalTypes } from '../../../../components/ScoreModal/modalTypes';
import RecordCard from '../RecordCard/RecordCard';
import { getManScoreRecordList } from '../../../../services';
import styles from './index.less';

const ScoreRec = ({ id, activeKey, refreshComp }) => {
    const [isManScore, setIsManScore] = useState(true);
    const [manSummaryData, setManSummaryData] = useState({});
    const [modalData, setModalData] = useState();
    const [modalVisible, setModalVisible] = useState(false);
    const [modalType, setModalType] = useState('');
    const [avatarUrlMap, setAvatarUrlMap] = useState({});
    const [manScoreLoading, setManScoreLoading] = useState(false);
    const [loading, setLoading] = useState(false);
    const [recordData, setRecordData] = useState([]);

    const switchButton = (
        <div className={styles.recordSwitch}>
            <span className={cn({ [styles.active]: isManScore })} onClick={() => setIsManScore(true)}>
                人工评分记录
            </span>
            <span className={cn({ [styles.active]: !isManScore })} onClick={() => setIsManScore(false)}>
                自动化评分记录
            </span>
        </div>
    );

    const toFixOne = num => {
        if (!num) {
            return 0;
        }
        return Number(num).toFixed(1);
    };

    const getResolveResult = result => {
        const processedResult = Number(result).toFixed(1);
        const base = Math.floor(processedResult);
        if (base === 5) return base;
        const floatNumber = (processedResult * 10) % 10;
        if (floatNumber < 3) {
            return base;
        }
        if (floatNumber < 8) {
            return base + 0.5;
        }
        return base + 1;
    };

    const getResultNode = result => (
        <>
            <div>
                综合评分
                <span className={styles.score}>{result ? `：${toFixOne(result)}` : ''}</span>
            </div>
            <Rate allowHalf disabled value={getResolveResult(result)}></Rate>
        </>
    );

    const handleDetail = (resultData, isReScore) => {
        setModalData(resultData);
        if (isReScore) {
            setModalType(modalTypes.RE_SCORE_DETAIL.key);
        } else {
            setModalType(modalTypes.SCORE_DETAIL.key);
        }
        setModalVisible(true);
    };

    const emptyBox = <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;

    const manScore = (
        <>
            <div className={styles.summary}>
                <span>
                    评分人数：
                    <span className={styles.number}>
                        <span>{manSummaryData.scoreTotalNumb}</span>人
                    </span>
                    （待评：
                    <span>{manSummaryData.unfinishNumb}</span>
                    人，已评
                    <span>{manSummaryData.finishNumb}</span>
                    人，放弃评分
                    <span>{manSummaryData.abandonNumb}</span>
                    人）
                </span>
                <span>
                    人工平均综合评分：
                    <span className={styles.number} style={{ marginRight: '17px' }}>
                        {toFixOne(manSummaryData.artificialAverageScore)}
                    </span>
                    权重占比：
                    <span className={styles.number}>
                        <span>{manSummaryData.artificialWeight}</span>%
                    </span>
                </span>
            </div>
            {recordData.map(record => {
                const finalScore = (() => {
                    if (record.reScoreDetails?.length > 0) {
                        return record.reScoreDetails[record.reScoreDetails.length - 1].comprehensiveScore;
                    }
                    return record.comprehensiveScore;
                })();
                return (
                    <RecordCard
                        record={record}
                        getResolveResult={getResolveResult}
                        avatarUrlMap={avatarUrlMap}
                        handleDetail={handleDetail}
                        finalScore={finalScore}
                        result={getResultNode(finalScore)}
                        toFixOne={toFixOne}
                        loading={loading}
                    />
                );
            })}
        </>
    );
    React.useEffect(() => {
        if (activeKey === 'scoreRec') {
            const getRecordData = async query => {
                setLoading(true);
                const res = await getManScoreRecordList(query);
                setLoading(false);
                if (res.code === 10000) {
                    setRecordData(res.data || []);
                }
            };
            getRecordData({ taskId: Number(id) });
        }
    }, [activeKey, refreshComp]);
    React.useEffect(() => {
        const getManSummaryData = async tskId => {
            setManScoreLoading(true);
            const res = await request(`/api/oa/v1/work/task/score/${tskId}/score_detail`);
            setManScoreLoading(false);
            if (res.code === 10000) {
                setManSummaryData(res.data || {});
            }
        };
        getManSummaryData(id);
    }, []);
    React.useEffect(() => {
        if (recordData.length > 0) {
            const employeeCodeList = (() => {
                const ret = [];
                function next(list) {
                    list.forEach(item => {
                        ret.push(item.employeeCode);
                        if (item.reScoreDetails?.length > 0) {
                            next(item.reScoreDetails);
                        }
                    });
                }
                next(recordData);
                return ret;
            })();
            const getAvatarUrl = async () => {
                const res = await request('/api/uc/org/employee/v1/avatar/list', {
                    method: 'POST',
                    data: employeeCodeList
                });
                if (res.code === 10000 && Array.isArray(res.data)) {
                    const urlMap = res.data.reduce((prev, curr) => {
                        const newPrev = { ...prev };
                        newPrev[curr.employeeCode] = curr.avatarFile;
                        return newPrev;
                    }, {});
                    setAvatarUrlMap(urlMap);
                }
            };
            getAvatarUrl();
        }
    }, [recordData]);
    return (
        <>
            <div className={styles.topLine}>
                <div>{switchButton}</div>
                <div>
                    合计平均综合评分：
                    <span className={styles.totalNumber}>{toFixOne(manSummaryData.totalAverageScore)}</span>
                </div>
            </div>
            <div className={styles.recordWrap}>
                {isManScore && (
                    <Spin spinning={manScoreLoading}>
                        {recordData.length === 0 && <div style={{ height: '100%' }}> {emptyBox}</div>}
                        {recordData.length > 0 && <div className={styles.scoreContent}>{manScore}</div>}
                    </Spin>
                )}
                {!isManScore && <div style={{ height: '100%' }}> {emptyBox}</div>}
            </div>

            <ScoreModal
                data={modalData}
                visible={modalVisible}
                type={modalType}
                setVisible={setModalVisible}
                isDetail
            ></ScoreModal>
        </>
    );
};

export default ScoreRec;
